package com.moxiao.yfjh.module.blind.common;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.moxiao.yfjh.framework.common.util.jpush.JgPushSendUrl;
import com.moxiao.yfjh.framework.common.util.jpush.JgPushSendVo;
import com.moxiao.yfjh.module.blind.controller.admin.member.vo.BlindMemberUserUpdateReqVO;
import com.moxiao.yfjh.module.blind.controller.admin.memberSayHello.vo.MemberSayhelloCreateReqVO;
import com.moxiao.yfjh.module.blind.controller.admin.memberSayHello.vo.MemberSayhelloUpdateReqVO;
import com.moxiao.yfjh.module.blind.controller.app.controller.user.vo.InitFaceVerifyReqVo;
import com.moxiao.yfjh.module.blind.controller.app.controller.user.vo.MemberUserAuthVO;
import com.moxiao.yfjh.module.blind.service.member.BlindMemberUserService;
import com.moxiao.yfjh.module.blind.service.memberSayHello.MemberSayhelloService;
import com.moxiao.yfjh.module.blind.utils.aliyun.AliDemo;
import com.moxiao.yfjh.module.system.sms.utils.GreenScanUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.jetbrains.annotations.NotNull;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Type;
import java.util.*;

import static com.moxiao.yfjh.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static com.moxiao.yfjh.module.system.mq.kafka.KafkaProducer.*;


/**
 * 会员用户认证
 *
 * @author mx
 */
@Component
@Slf4j
public class BlindMemberUserAuth {

    @Resource
    private BlindMemberUserService blindMemberUserService;
    @Resource
    private BlindNotifyMessageUtils blindNotifyMessageUtils;
    @Resource
    private InitFaceVerifyUtils initFaceVerifyUtils;
    @Resource
    private GreenScanUtils greenScanUtils;
    @Resource
    private MemberSayhelloService memberSayhelloService;
    @Resource
    private TencentCloudImUtil tencentCloudImUtil;
    @Resource
    private JgPushSend jgPushSend;

    @KafkaListener(topics = {KAFKA_BLIND_MEMBER_USER_AUTH})
    public void listenAvatarAuthConsumer(ConsumerRecord<?, ?> record) {
        Optional.ofNullable(record.value())
                .ifPresent(
                        message -> {
                            log.info("【消费者接收用户头像实名认证: {}】", message);
                            cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(message);
                            String userId = jsonObject.get("userId").toString();
                            String avatar = jsonObject.get("Avatar").toString();
                            String idNumber = jsonObject.get("IdNumber").toString();
                            String name = jsonObject.get("Name").toString();
                            Map<String, Object> resultMap = AliDemo.getResult(avatar, idNumber, name);
                            log.info("人脸识别认证返回:{}", resultMap);
                            if (resultMap != null) {
                                String code = resultMap.get("ResultCode").toString();
                                //TODO 400：参数错误/403：套餐已用尽
                                if (!code.equals("400") && !code.equals("403")) {
                                    String body = resultMap.get("ResultBody").toString();
                                    // 使用 Gson 解析 JSON 字符串为 Map
                                    Gson gson = new Gson();
                                    Type type = new TypeToken<Map<String, Object>>() {
                                    }.getType();
                                    Map<String, Object> ResultBody = gson.fromJson(body, type);
                                    String result_code = ResultBody.get("result_code").toString();
                                    if (result_code.equals("1001") || result_code.equals("1002")) {
                                        //TODO 认证成功，修改认证状态
                                        MemberUserAuthVO authVO = new MemberUserAuthVO();
                                        authVO.setAvatarAuth((byte) 1);
                                        authVO.setId(Long.valueOf(userId));
                                        blindMemberUserService.updateAvatarAuth(authVO);
                                        //发送通知
                                        blindNotifyMessageUtils.createVerifySelfieMessage(Long.valueOf(userId));
                                    } else {
                                        //TODO 认证失败，修改认证状态
                                        MemberUserAuthVO authVO = new MemberUserAuthVO();
                                        authVO.setAvatarAuth((byte) 2);
                                        authVO.setId(Long.valueOf(userId));
                                        blindMemberUserService.updateAvatarAuth(authVO);
                                        //发送通知
                                        blindNotifyMessageUtils.createVerifySelfieErrorMessage(Long.valueOf(userId));
                                    }
                                } else {
                                    //发送通知
                                    blindNotifyMessageUtils.createVerifySelfieMessage(Long.valueOf(userId));
                                }
                            } else {
                                //发送通知
                                blindNotifyMessageUtils.createVerifySelfieMessage(Long.valueOf(userId));
                            }

                        });
    }

    /**
     * 用户身份认证消费
     *
     * @param record
     */

    @KafkaListener(topics = {KAFKA_BLIND_MEMBER_USER_ID_CARD_AUTH})
    public void listenIdCardAuthConsumer(ConsumerRecord<?, ?> record) {
        Optional.ofNullable(record.value())
                .ifPresent(
                        message -> {
                            log.info("【消费者接收用户身份认证 : {}】", message);
                            cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(message);
                            String userId = jsonObject.get("userId").toString();
                            String certName = jsonObject.get("certName").toString();
                            String certNo = jsonObject.get("certNo").toString();
                            String metaInfo = jsonObject.get("metaInfo").toString();
                            InitFaceVerifyReqVo initFaceVerifyReqVo = new InitFaceVerifyReqVo();
                            initFaceVerifyReqVo.setUserId(Long.valueOf(userId));
                            initFaceVerifyReqVo.setCertName(certName);
                            initFaceVerifyReqVo.setCertNo(certNo);
                            initFaceVerifyReqVo.setMetaInfo(metaInfo);
                            Map<String, String> map = initFaceVerifyUtils.initFaceVerify(initFaceVerifyReqVo);
                            if (MapUtils.isNotEmpty(map)) {
                                String certifyId = map.get("certifyId");
                                if (StringUtils.isEmpty(certifyId)) {
                                    log.error("身份认证失败！-{}", map.get("message"));
                                } else {
                                    log.info("身份认证成功！-{}", map.get("message"));
                                }
                                //TODO 认证成功，修改认证状态，修改用户的性别，年龄，生日，星座
                                MemberUserAuthVO authVO = initFaceVerifyUtils.getIdCard(initFaceVerifyReqVo.getCertNo());
                                authVO.setId(getLoginUserId());
                                blindMemberUserService.updateIdNumberAuth(authVO);
                            }
                        });
    }

    /**
     * 内心独白
     */
    @KafkaListener(topics = {KAFKA_BLIND_MEMBER_USER_INNER_MONOLOGUE})
    public void listenInnerMonologueConsumer(ConsumerRecord<?, ?> record) {
        Optional.ofNullable(record.value())
                .ifPresent(
                        message -> {
                            log.info("【消费者接收内心独白 : {}】", message);
                            cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(message);
                            String content = jsonObject.get("content").toString();
                            String id = jsonObject.get("id").toString();
                            try {
                                Map map = greenScanUtils.greeTextScan(content);
                                if (Objects.equals(map.get("suggestion"), "pass")) {
                                    blindMemberUserService.updateContent(Long.valueOf(id), content);
                                } else {
                                    log.info("内心独白检测未通过:{}", map);
                                }
                            } catch (Exception e) {
                                log.error("内心独白消费异常：{}", e.getMessage());
                            }
                        });
    }

    private @NotNull JgPushSendVo getJgPushSendVo(String issue, String content) {
        JgPushSendVo jgPushSendVo = new JgPushSendVo();
        List<String> alias = new ArrayList<>();
        alias.add(issue);
        jgPushSendVo.setContent(jgPushSend.getStr(content));
        jgPushSendVo.setNotificationTitle("您收到了一个打招呼");
        jgPushSendVo.setMsgTitle("您收到了一个打招呼");
        jgPushSendVo.setAlias(alias);
        jgPushSendVo.setUrl("pages/index/details/details?Id=" + issue);
        JgPushSendUrl sendUrl = new JgPushSendUrl();
        sendUrl.setUrl("pages/index/details/details?Id=" + issue);
        sendUrl.setType(1);
        jgPushSendVo.setSendUrl(sendUrl);
        return jgPushSendVo;
    }

    /**
     * 内心独白
     */
    @KafkaListener(topics = {KAFKA_BLIND_SAY_HELLO})
    public void listenSayHelloConsumer(ConsumerRecord<?, ?> record) {
        Optional.ofNullable(record.value())
                .ifPresent(
                        message -> {
                            log.info("【消费者接收打招呼 : {}】", message);
                            cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(message);
                            String content = jsonObject.get("content").toString();
                            String backContent = jsonObject.get("backContent").toString();
                            String id = jsonObject.get("id").toString();
                            String receive = jsonObject.get("receive").toString();
                            String issue = jsonObject.get("issue").toString();
                            try {
                                Map map = greenScanUtils.greeTextScan(content);
                                if (Objects.equals(map.get("suggestion"), "pass")) {
                                    MemberSayhelloUpdateReqVO updateReqVO = new MemberSayhelloUpdateReqVO();
                                    updateReqVO.setBackContent(backContent);
                                    updateReqVO.setContent(content);
                                    updateReqVO.setId(Long.valueOf(id));
                                    memberSayhelloService.updateMemberSayhello(updateReqVO);
                                    // 发送通知
                                    MemberSayhelloCreateReqVO createReqVO = new MemberSayhelloCreateReqVO();
                                    createReqVO.setReceive(receive);
                                    createReqVO.setIssue(issue);
                                    blindNotifyMessageUtils.createSayHelloMessage(createReqVO);
                                    // 推送打招呼通知！
                                    JgPushSendVo jgPushSendVo = getJgPushSendVo(issue, content);
                                    jgPushSend.sendToAllAndroid(jgPushSendVo);
                                    log.info("打招呼通过检测:{}", map);
                                } else {
                                    memberSayhelloService.deleteMemberSayhello(Long.valueOf(id));
                                    log.info("打招呼未通过检测:{}", map);
                                }
                            } catch (Exception e) {
                                log.error("打招呼消费异常：{}", e.getMessage());
                            }
                        });
    }


    /**
     * 用户昵称
     */
    @KafkaListener(topics = {KAFKA_BLIND_NICK_NAME})
    public void listenNickNameConsumer(ConsumerRecord<?, ?> record) {
        Optional.ofNullable(record.value())
                .ifPresent(
                        message -> {
                            log.info("【消费者接收用户昵称消息 : {}】", message);
                            cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(message);
                            String nickName = jsonObject.get("nickName").toString();
                            String old_nickName = jsonObject.get("old_nickName").toString();
                            String id = jsonObject.get("id").toString();
                            try {
                                Map map = greenScanUtils.greeTextScan(nickName);
                                if (Objects.equals(map.get("suggestion"), "pass")) {
                                    BlindMemberUserUpdateReqVO updateReqVO = new BlindMemberUserUpdateReqVO();
                                    updateReqVO.setId(Long.valueOf(id));
                                    updateReqVO.setNickname(nickName);
                                    blindMemberUserService.updateMemberUser(updateReqVO);
                                    //IM资料更新
                                    tencentCloudImUtil.portraitSet(id, nickName, null);
                                    log.info("用户昵称通过检测:{}", map);
                                } else {
                                    BlindMemberUserUpdateReqVO updateReqVO = new BlindMemberUserUpdateReqVO();
                                    updateReqVO.setId(Long.valueOf(id));
                                    updateReqVO.setNickname(old_nickName);
                                    blindMemberUserService.updateMemberUser(updateReqVO);
                                    blindNotifyMessageUtils.createNicknameMessage(Long.valueOf(id));
                                    log.error("用户昵称未通过检测:{}", map);
                                }
                            } catch (Exception e) {
                                log.error("用户昵称消费异常：{}", e.getMessage());
                            }
                        });
    }
}


